<template>
  <div>
    <div class="doumee-filter">
      <el-form inline
        label-suffix="："
        @submit.native.prevent>
        <el-form-item :label="$t('message.kcmc')"><el-input v-model="form.courseName"
            @keyup.enter.native="getList(1)"
            :placeholder="$t('message.qsr') + $t('message.kcmc')"
            clearable /></el-form-item>
        <el-form-item :label="$t('message.rq')"><el-input v-model="time"
            readonly
            style="width: 250px" /></el-form-item>
        <el-form-item :label="$t('message.skjl2')">
          <el-select v-model="form.teacherId"
            clearable
            readonly
            class="w200">
            <el-option v-for="item in coachList"
              :key="item.teacherId"
              :value="item.teacherId"
              :label="item.teacherName" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-preventReClick
            type="primary"
            @click="weekChange(1)">{{ $t('message.syz') }}</el-button>
          <el-button v-preventReClick
            type="primary"
            @click="weekChange(2)">{{ $t('message.xyz') }}</el-button></el-form-item>
        <el-form-item>
          <el-button v-preventReClick
            type="primary"
            @click="getList">{{ $t('message.cz') }}</el-button>
          <el-button v-preventReClick
            @click="clearList">{{ $t('message.clear') }}</el-button></el-form-item>
      </el-form>
    </div>
    <div class="table">
      <div class="flex-c tableUl">
        <div v-for="(weeks, dex) in weekList"
          :key="dex"
          class="tableLi">
          <div class="tableTitle">{{ weeks.label }}</div>
          <template v-if="list.length > 0">
            <div v-for="(e, index) in list[dex].courseList"
              :key="index"
              class="tableCnt"
              :style="
                'background-color: ' +
                  colorList[idList.indexOf(e.courseId)].color
              "
              @click="showDetail(e)">
              <div>
                {{ e.courseName }}
                <span>({{ e.studentNum || 0 }}{{ $t('message.ren') }})</span>
              </div>
              <div>（{{ e.beginTime }}~{{ e.endTime }}）</div>
              <div v-if="e.teacherName">{{ $t('message.jiaolian') }}：（{{ e.teacherName }}）</div>
              <div v-if="e.assistantName">{{ $t('message.zhujiao') }}：（{{ e.assistantName }}）</div>
            </div>
          </template>
        </div>
      </div>
      <div v-if="list.length == 0"
        style="
          line-height: 60px;
          text-align: center;
          color: #909399;
          font-size: 14px;
        ">
        {{ $t('message.zwsj') }}
      </div>
    </div>
    <el-drawer :title="$t('message.ksxq')"
      :visible.sync="showDetails"
      size="1100px">
      <div class="header-info">
        <div class="property-title">{{ $t('message.ksxx') }}</div>
        <div class="course-edit">
          <el-button v-if="!edit"
            type="primary"
            @click="showSchedule">{{ $t('message.edit') }}</el-button>
          <el-button v-if="edit"
            v-preventReClick
            type="primary"
            @click="preservation">{{ $t('message.baocun') }}</el-button>
          <el-button v-preventReClick
            @click="updateStatus">{{ $t('message.del') }}</el-button>
        </div>
      </div>
      <el-form ref="ruleForm"
        :model="detail"
        class="siteDetails"
        label-suffix="：">
        <el-form-item :label="$t('message.kcmc')"
          class="form-item">
          <span>{{ detail.courseName }}</span>
        </el-form-item>
        <el-form-item v-if="detail.className"
          :label="$t('message.bjmc')"
          class="form-item">
          <span>{{ detail.className }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.jiaolian')"
          class="form-item">
          <el-select v-if="edit"
            v-model="detail.teacherId"
            clearable
            readonly
            class="w200">
            <el-option v-for="item in coachList"
              :key="item.teacherId"
              :value="item.teacherId"
              :label="item.teacherName" />
          </el-select>
          <span v-if="!edit">{{ detail.teacherName || '-' }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.zjjl')"
          class="form-item">
          <el-select v-if="edit"
            v-model="detail.assistantIds"
            clearable
            readonly
            class="w200">
            <el-option v-for="item in coachList"
              :key="item.teacherId"
              :value="item.teacherId"
              :label="item.teacherName" />
          </el-select>
          <span v-if="!edit">{{ detail.assistantName || '-' }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.skrq')"
          class="form-item">
          <el-date-picker v-if="edit"
            v-model="detail.classDay"
            type="date"
            class="w200"
            value-format="yyyy-MM-dd" />
          <span v-if="!edit">{{ detail.classDay }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.sksj')"
          class="form-item">
          <el-time-picker v-if="edit"
            v-model="detail.time"
            is-range
            value-format="HH:mm"
            format="HH:mm"
            :placeholder="$t('message.xzsj')" />
          <span v-if="!edit">{{ detail.beginTime }} - {{ detail.endTime }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.skdd')"
          class="form-item">
          <el-input v-if="edit"
            v-model="detail.site"
            class="w200" />
          <span v-if="!edit">{{ detail.site }}</span>
        </el-form-item>
        <el-form-item v-if="detail.classStudentNum"
          :label="$t('message.bjrs')"
          class="form-item">
          <!-- <el-input v-if="edit" v-model="detail.name" /> -->
          <span>{{ detail.classStudentNum }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.bmrs')"
          class="form-item">
          <span>{{ detail.studentNum }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.qdrs')"
          class="form-item">
          <span>{{ detail.signInNum }}</span>
        </el-form-item>
      </el-form>
      <div class="line-style" />
      <div class="property-title"
        style="margin-top: 20px">{{ $t('message.xyxx') }}</div>
      <div class="doumee-filter">
        <el-form inline
          label-suffix="："
          @submit.native.prevent>
          <el-form-item :label="$t('message.xyxm')"><el-input v-model="filters.studentName"
              :placeholder="$t('message.qsr') + $t('message.xyxm')"
              clearable /></el-form-item>
          <el-form-item :label="$t('message.memberInfo')"><el-input v-model="filters.memberInfo"
              :placeholder="$t('message.hy2')"
              clearable /></el-form-item>
          <el-form-item><el-button v-preventReClick
              type="primary"
              @click="doFilter">{{ $t('message.cz') }}</el-button>
            <el-button v-preventReClick
              @click="clearFilter">{{ $t('message.clear') }}</el-button></el-form-item>
        </el-form>
      </div>
      <el-table ref="tableDetailRef"
        :data="tableChangeData"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table margin-t-10">
        <el-table-column align="center"
          min-width="120"
          show-overflow-tooltip
          :label="$t('message.xyxm')"
          prop="studentName" />
        <el-table-column align="center"
          min-width="250"
          show-overflow-tooltip
          :label="$t('message.memberInfo')">
          <template slot-scope="scope">
            <span>{{ scope.row.memberName }}</span>
            <span>-{{ scope.row.memberPhone }}</span>
            <span>-{{ scope.row.memberCard }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center"
          min-width="140"
          :label="$t('message.xyzjh')"
          prop="studentIdCard"
          show-overflow-tooltip />
        <el-table-column align="center"
          min-width="100"
          :label="$t('message.qdzt')"
          prop="signIn"
          show-overflow-tooltip>
          <template slot-scope="scope">
            {{
              scope.row.signIn == "0"
                ? $t('message.wqd')
                : scope.row.signIn == "1"
                  ? $t('message.yqd')
                  : ""
            }}
          </template>
        </el-table-column>
        <el-table-column align="center"
          min-width="120"
          show-overflow-tooltip
          :label="$t('message.qdr')"
          prop="signInUser">
          <template slot-scope="scope">
            <span v-if="scope.row.signIn == '1'">{{
              scope.row.signInUser
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center"
          :label="$t('message.qdsj')"
          min-width="160"
          prop="signInTime"
          show-overflow-tooltip />
        <el-table-column :label="$t('message.caozuo')"
          align="center"
          min-width="120"
          fixed="right">
          <template slot-scope="scope">
            <div class="flex-cc">
              <el-button v-if="scope.row.signIn == '0'"
                type="text"
                @click="singup(scope.row)">{{ $t('message.qiandao') }}</el-button>
              <el-button v-if="scope.row.signIn != '0'"
                type="text"
                @click="singup(scope.row, '1')">{{ $t('message.qxqd') }}</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Paginations :total="total"
        :page="pageNo"
        @SizeChange="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-drawer>
    <ScheduleCardAdd v-if="isShowScheduleCardAdd"
      ref="ScheduleCardAddRef"
      @close="isShowScheduleCardAdd = false"
      @success="getDetail" />
  </div>
</template>

<script>
import {
  teacherList,
  courseTimeAllList,
  detailCourseTime,
  addCourseTime,
  deleteCourseTime,
  studentSignInPC,
  courseTimeStudentList
} from '@/api'
import store from '@/store'
import ScheduleCardAdd from '@/views/offlinecourses/scheduleCardAdd'
export default {
  components: {
    ScheduleCardAdd
  },
  data () {
    return {
      isShowScheduleCardAdd: false,
      pickerOptions: {
        disabledDate (time) {
          return (
            time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
          )
        }
      },
      modalDialog: store.getters.dialog,
      time: '',
      weekList: [],
      listLoading: false,
      form: {},
      integrated: false,
      showDetails: false,
      detail: {},
      statusList: [
        { value: '0', label: this.$t('message.wqd') },
        { value: '1', label: this.$t('message.yqd') }
      ],
      coachList: [],
      edit: false,
      list: [],
      filters: {},
      tableChangeData: [],
      total: null,
      pageNo: 1, // 当前页
      pageSize: 10, // 每页显示条目数
      tableData: [],
      colorList: [],
      idList: []
    }
  },
  created () {
    this.activeDate = this.formatDate(new Date()).value
    this.setDate(new Date())
    this.getTeachList()
  },
  methods: {
    showSchedule () {
      this.isShowScheduleCardAdd = true
      this.$nextTick(() => {
        this.$refs.ScheduleCardAddRef.isShowModal = true
        if (this.detail.teacherId) {
          this.$refs.ScheduleCardAddRef.teacherId = this.detail.teacherId
        }
        this.$refs.ScheduleCardAddRef.site = this.detail.site
        this.$refs.ScheduleCardAddRef.courseId = this.detail.courseId
        this.$refs.ScheduleCardAddRef.timeId = this.detail.timeId
        this.$refs.ScheduleCardAddRef.param = { ...this.detail }
        this.$refs.ScheduleCardAddRef.getDetail()
      })
    },
    singup (row, val) {
      studentSignInPC({
        param: {
          id: row.id,
          cancel: val || null
        }
      })
        .then(res => {
          if (res.errorCode === '000000') {
            this.$message.success(val === '1' ? this.$t('message.qxqdcg') : this.$t('message.qdcg'))
            this.getDetail()
          } else {
            this.$message.error(res.errMsg)
          }
        })
    },
    getTeachList () {
      const venueId = sessionStorage.getItem('venueId')
      teacherList({ param: { venueId, teacherType: '0', status: '1', isOnJob: '1' } })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.coachList = res.recordList
        })
    },
    updateStatus (e) {
      const that = this
      this.$confirm(this.$t('message.sctc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          deleteCourseTime({ param: { timeId: that.detail.timeId } })
            .then((res) => {
              if (res.errorCode === '000000') {
                that.$message.success(this.$t('message.delcg'))
                that.edit = false
                that.showDetails = false
                that.getList()
              }
            })
        })
    },
    doFilter () {
      this.pageNo = 1
      this.getMembersList()
      this.getStu()
    },
    clearFilter () {
      this.pageNo = 1
      this.filters = {}
      this.getMembersList()
      this.getStu()
    },
    // 分页
    handleSizeChange (val) {
      this.pageSize = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.getMembersList()
    },
    // 前端分页+模糊查询
    getMembersList () {
      const that = this
      if (!this.tableData) {
        this.tableChangeData = []
        return
      }
      const tableChangeData = this.tableData.filter((item) =>
        that.filters.name ? item.studentName.includes(that.filters.name) : item
      )
      // 过滤分页
      this.tableChangeData = tableChangeData.filter((item, index) =>
        index < this.pageNo * this.pageSize && index >= this.pageSize * (this.pageNo - 1)
      )
      // 分页的总数据
      this.total = tableChangeData.length
    },
    showDetail (e) {
      this.showDetails = true
      this.edit = false
      this.detail.timeId = e.timeId
      this.getDetail()
      this.$nextTick(() => {
        this.$refs.tableDetailRef.doLayout()
      })
    },
    getDetail () {
      detailCourseTime({ param: { timeId: this.detail.timeId } })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.detail = {
              ...res.record,
              assistantIds: res.record.assistantIds ? res.record.assistantIds : [],
              time: [res.record.beginTime, res.record.endTime]
            }
          }
        })
      this.getStu()
    },
    // 获取学员
    getStu () {
      courseTimeStudentList({ param: { ...this.filters, timeId: this.detail.timeId } })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.tableData = res.recordList
          this.getMembersList()
        })
    },
    // 获取星期
    calculation (s) {
      return s < 10 ? '0' + s : s
    },
    formatDate (date) {
      const year = date.getFullYear() + '-'
      const month = this.calculation(date.getMonth() + 1) + '-'
      const day = this.calculation(date.getDate())
      const week = [this.$t('message.z7'), this.$t('message.z1'), this.$t('message.z2'), this.$t('message.z3'), this.$t('message.z4'), this.$t('message.z5'), this.$t('message.z6')][
        date.getDay()
      ]
      return {
        label: week + ' (' + year + month + day + ')',
        value: year + month + day,
        old: new Date(date)
      }
    },
    addDate (date, n) {
      date.setDate(date.getDate() + n)
      return date
    },
    setDate (date) {
      var week = date.getDay() - 1
      if (week === -1) {
        week = 6
      }
      date = this.addDate(date, week * -1)
      const arr = []
      for (var i = 0; i < 7; i++) {
        arr[i] = this.formatDate(i === 0 ? date : this.addDate(date, 1))
      }
      this.weekList = arr
      this.time = arr[0].value + '~' + arr[6].value
      this.getList()
    },
    weekChange (e) {
      if (e === 1) {
        this.setDate(this.addDate(this.weekList[0].old, -7))
      } else {
        this.setDate(this.addDate(this.weekList[0].old, 7))
      }
    },
    preservation () {
      const param = { ...this.detail }
      param.classNum = Number(param.classNum)
      if (param.time.length > 0) {
        param.beginTime = param.time[0]
        param.endTime = param.time[1]
      }
      addCourseTime({
        param
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.$message.success(this.$t('message.editcg'))
            this.edit = false
            this.showDetails = false
            this.getList()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    clearList () {
      this.form = {}
      this.getList()
    },
    // 获取列表
    getList () {
      courseTimeAllList({
        param: {
          ...this.form,
          begin: this.weekList[0].value,
          end: this.weekList[6].value
        }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        this.list = res.recordList || []
        const arr = res.recordList || []
        const arrs = []
        const color = []
        arr.forEach((e) => {
          e.courseList.forEach((s) => {
            if (arrs.indexOf(s.courseId) === -1) {
              arrs.push(s.courseId)
            }
          })
        })
        arrs.forEach((e) => {
          const obj = {
            id: e,
            color: this.getRandomColor()
          }
          color.push(obj)
        })
        this.idList = arrs
        this.colorList = color
      })
    },
    getRandom (min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    // 返回我们要的颜色
    getRandomColor () {
      var c1 = this.getRandom(0, 255)
      var c2 = this.getRandom(0, 255)
      var c3 = this.getRandom(0, 255)
      return 'rgba(' + c1 + ',' + c2 + ',' + c3 + ', 0.5)'
    }
  }
}
</script>
<style lang="scss" scoped>
.siteDetails {
  display: flex;
  flex-wrap: wrap;
  .form-item {
    width: 33.3%;
    display: flex;
    margin-bottom: 5px;
    ::v-deep .el-form-item__content {
      flex: 1;
    }
    ::v-deep .el-date-editor {
      width: 100%;
    }
  }
}
.table {
  border-right: none;
  .tableUl {
    align-items: flex-start;
  }
  .tableLi {
    flex: 1;
    text-align: center;
    margin: 3px;
    align-items: center;
    &:first-of-type {
      margin-left: 0;
    }
    &:last-of-type {
      margin-right: 0;
    }
    .tableTitle {
      line-height: 40px;
      font-weight: bolder;
      font-size: 13px;
      flex: 1;
      color: #111111;
      background-color: #f4f7fc;
    }
    .tableCnt {
      flex: 1;
      padding: 20px 0;
      margin-top: 6px;
      font-size: 13px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      div {
        line-height: 1.5;
      }
    }
  }
}
.header-info {
  display: flex;
  margin: 0 auto;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 20px;
  margin-bottom: 20px;
  .course-edit {
    text-align: center;
    margin-right: 20px;
  }
}
</style>
